package org.graffitidiary.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.graffitidiary.R;
import org.graffitidiary.adapter.ItemFileAdapter;
import org.graffitidiary.bean.Brush;
import org.graffitidiary.bean.FileInfo;
import org.graffitidiary.bean.Userinfo;
import org.graffitidiary.framework.ui.ActionBarActivity;
import org.graffitidiary.manager.Dbs;
import org.graffitidiary.utils.FileMethod;
import org.graffitidiary.utils.GloableParams;
import org.graffitidiary.utils.ToastUtil;
import org.graffitidiary.view.SecondSurfaceView;
import org.json.JSONArray;
import org.json.JSONObject;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.exception.DbException;
import com.okhttplib.HttpInfo;
import com.okhttplib.OkHttpUtil;
import com.okhttplib.callback.ProgressCallback;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

public class FileListActivity extends ActionBarActivity{
    private ListView lv_files;
    ItemFileAdapter itemFileAdapter;
    String path;//得到文件路径

    LinearLayout linearLayout;
    SecondSurfaceView surfaceView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showBar();
        setBarTitle("我的涂鸦");
        showBarRightImgBtn();
        setBarRightBackgroundResource(R.drawable.huatu);
        showBarNetBtn();
        setBarLeftNetImg(R.drawable.net);
        checkLogin();

    }

    @Override
    protected int setLayout() {
        return R.layout.activity_upload_file;
    }


    @Override
    protected void initViews() {
        lv_files = (ListView) findViewById(R.id.lv_files);
        surfaceView = (SecondSurfaceView) findViewById(R.id.sf_no_file_use);
        linearLayout = (LinearLayout) findViewById(R.id.ll_no_file_tip);
        linearLayout.setOnClickListener(this);
        getAllLocalData();
//		path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/GraffitiDiary/data/";
//
//		itemFileAdapter = new ItemFileAdapter(GetXML(path), FileListActivity.this);
//		lv_files.setAdapter(itemFileAdapter);
//
        lv_files.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String fileName = itemFileAdapter.getItem(position).getFileName();
                String filePath = itemFileAdapter.getItem(position).getFilePath();
                String fileNick = itemFileAdapter.getItem(position).getFileNick();
                int fileState = itemFileAdapter.getItem(position).getFileState();
                int fileid = itemFileAdapter.getItem(position).getId();
                if(FileMethod.fileIsExists(itemFileAdapter.getItem(position).getFilePath())){
                    Intent intent = new Intent(FileListActivity.this, AutoDrawActivity.class);
                    intent.putExtra("fileName", fileName);
                    intent.putExtra("filePath", filePath);
                    intent.putExtra("filePath", filePath);
                    intent.putExtra("fileNick", fileNick);
                    intent.putExtra("fileState", fileState + "");
                    intent.putExtra("id", fileid + "");
                    startActivity(intent);
                }else{
                    ToastUtil.showShortToast("文件不存在");
                    deleteFileInfo(fileid);
                    getAllLocalData();
                }

            }
        });
    }

    List<FileInfo> list;
    /**
     * 获取本地所有数据
     */
    private void getAllLocalData() {
        list = new ArrayList<FileInfo>();
        Dbs.getDb(this);
        try {
            list = Dbs.getDb().findAll(FileInfo.class);
            Dbs.close();
            if(null == list || list.size() == 0){
                linearLayout.setVisibility(View.VISIBLE);
                lv_files.setVisibility(View.GONE);
                path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/GraffitiDiary/data";
//				if(FileMethod.getFileOrFilesSize(path) > 0){
//					FileMethod.deleteFolderFile(path, true);
//				}
            }else{
                lv_files.setVisibility(View.VISIBLE);
                linearLayout.setVisibility(View.GONE);
                itemFileAdapter = new ItemFileAdapter(list);
                lv_files.setAdapter(itemFileAdapter);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    // 获取当前目录下所有的xml文件
    public static List<FileInfo> GetXML(String fileAbsolutePath) {
        List<FileInfo> datas = new ArrayList<FileInfo>();
        File file = new File(fileAbsolutePath);
        File[] subFile = file.listFiles();

        for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
            FileInfo fileInfo = new FileInfo();
            // 判断是否为文件夹
            if (!subFile[iFileLength].isDirectory()) {
                String filename = subFile[iFileLength].getName();
                String filePath = subFile[iFileLength].getPath();
                // 判断是否为xml结尾
                if (filename.trim().toLowerCase().endsWith(".xml")) {
                    fileInfo.setFileName(filename);
                    fileInfo.setFilePath(filePath);
                    datas.add(fileInfo);
                }
            }
        }
        return datas;
    }

    /**
     * 从数据库中查询用户是否已存在
     */
    private void checkLogin() {
        try {
            Dbs.getDb(this);
            Userinfo userinfo = Dbs.getDb().findFirst(Userinfo.class);
            Dbs.close();
            if(userinfo != null){
                GloableParams.token = userinfo.getToken();
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.bar_btn_right:
                startIntent(MainActivity.class);
                break;
            case R.id.bar_btn_left_net:

                if(!TextUtils.isEmpty(GloableParams.token)){
                    startIntent(GraffitiFriendActivity.class);
                }else{
                    showLoginDialog();
                }
                break;
            case R.id.ll_no_file_tip:
                startIntent(MainActivity.class);
                break;

            default:
                break;
        }
    }

    /**
     * 修改数据状态
     */
    private void deleteFileInfo(int id) {
        try {
            Dbs.getDb(this);
            FileInfo fileInfo = Dbs.getDb().findById(FileInfo.class, id);
            if(fileInfo != null){
                fileInfo.setFileState(1);
                Dbs.getDb().delete(fileInfo);
            }
            Dbs.close();
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getAllLocalData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        surfaceView.onDestory();
    }
}
